import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SpringLayout;

public class TestScrollPane {

	private static void createAndShowGUI() {
		// Main frame
		JFrame frame = new JFrame("Main Frame");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		
		// GridLayout with 50 JPanels
		JPanel panel = new JPanel(new GridLayout(0,5), false);
		JPanel containers[] = new JPanel[50];
		for (int i=0; i<50; i++) {
			containers[i] = new JPanel(new SpringLayout(), false);
			containers[i].setPreferredSize(new Dimension(100,100));
			containers[i].setBorder(BorderFactory.createTitledBorder("container["+i+"]"));
			panel.add(containers[i]);
		}

		// ScrollPane to add a scroll bar to the GridLayout
		JScrollPane scrollPane = new JScrollPane(panel);
		scrollPane.setBorder(BorderFactory.createTitledBorder("scrollPane"));
		scrollPane.setPreferredSize(new Dimension(640,400));
		
		// SpringLayout to fix the ScrollPane size
		JPanel mainPanel = new JPanel(new SpringLayout(), false);
		mainPanel.setPreferredSize(new Dimension(640,400));
		mainPanel.add(scrollPane);
		
		// Add everything to the frame, pack and show
		frame.getContentPane().add(mainPanel);
		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

}
